<?php
namespace Home\Library;

class WeChatPay{
    private $wx_data;
    public function __construct($wx_data)
    {
        $this->wx_data = $wx_data;
    }
    public function getParams($ProductParams=array()){
        extract($this->wx_data);
        $prepay_id = $this->generatePrepayId($ProductParams);
        $response = array(
            'appid'     => $appid,
            'partnerid' => $mchid,
            'prepayid'  => $prepay_id,
            'package'   => 'Sign=WXPay',
            'noncestr'  => $this->generateNonce(),
            'timestamp' => time(),
        );
        $response['sign'] = $this->calculateSign($response, $appkey);
        return $response;
    }

    private function generateNonce()
    {
        return md5(uniqid('', true));
    }

    private function calculateSign($arr, $key)
    {
        ksort($arr);

        $buff = "";
        foreach ($arr as $k => $v) {
            if ($k != "sign" && $k != "key" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");

        return strtoupper(md5($buff . "&key=" . $key));
    }

    private function generatePrepayId($params)
    {
        extract($this->wx_data);
        extract($params);
        $params = array(
            'appid' => $appid,
            'mch_id' => $mchid,
            'nonce_str' => $this->generateNonce(),
            'body' => 'Test product name',
            'out_trade_no' => time(),
            'total_fee' => 1,
            'spbill_create_ip' => '0.0.0.0',
            'notify_url' => '',
            'trade_type' => 'APP',
        );

        // add sign
        $params['sign'] = $this->calculateSign($params, $appkey);

        // create xml
        $xml = $this->getXMLFromArray($params);
        $result = $this->curlPost('https://api.mch.weixin.qq.com/pay/unifiedorder', $xml);
        $xml = simplexml_load_string($result);

        return (string)$xml->prepay_id;
    }
    /*const APPID = 'wx4e1218d20fd0aff3';
    const MCHID = '1319560001';
    const APP_KEY = 'z6016254szwlgdzswyxgsz6016254wlg';*/

    /**
     * Get xml from array
     */
    private function getXMLFromArray($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= sprintf("<%s>%s</%s>", $key, $val, $key);
            } else {
                $xml .= sprintf("<%s><![CDATA[%s]]></%s>", $key, $val, $key);
            }
        }

        $xml .= "</xml>";
        return $xml;
    }

    private function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}